'use client';

import React, { useState, useContext } from 'react';
import { 
  Input, 
  Button, 
  Card, 
  Table, 
  Badge, 
  Space
} from 'antd';
import { 
  PlayCircleOutlined
} from '@ant-design/icons';
import { MessageApiContext } from '../layout/MainLayout';
import { SiderMenuRefreshContext } from '../layout/SiderMenu';
import './ScanTool.css';
import { projectApi } from '@/services/projectApi';
import { scanResultApi } from '@/services/scanResultApi';

const ScanTool: React.FC = () => {
  const messageApi = useContext(MessageApiContext);
  const refreshSiderMenu = useContext(SiderMenuRefreshContext);
  const [ipInput, setIpInput] = useState('');
  const [scanning, setScanning] = useState(false);
  const [inputShake, setInputShake] = useState(false);
  const [tableData, setTableData] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [pageNum, setPageNum] = useState(1);
  const [projectId, setProjectId] = useState<number | null>(null);
  const PAGE_SIZE = 200;

  // 表格列定义
  const columns = [
    {
      title: 'IP地址',
      dataIndex: 'IP',
      key: 'IP',
    },
    {
      title: '端口号',
      dataIndex: 'Port',
      key: 'Port',
    },
    {
      title: '端口状态',
      dataIndex: 'PortStatus',
      key: 'PortStatus',
      render: (status: string) => (
        <Badge 
          status={status?.trim().toLowerCase() === 'open' ? 'success' : 'error'} 
          text={status?.trim().toLowerCase() === 'open' ? '开放' : '关闭'} 
        />
      ),
    },
    {
      title: '服务',
      dataIndex: 'Service',
      key: 'Service',
    },
    {
      title: '扫描时间',
      dataIndex: 'CreateTime',
      key: 'CreateTime',
      render: (t: string) => new Date(t).toLocaleString(),
    },
  ];

  // 校验IP或网段
  const isValidIpOrCidr = (input: string) => {
    // IPv4
    const ipRegex = /^(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){3}$/;
    // CIDR
    const cidrRegex = /^(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){3}\/(3[0-2]|[12]?\d)$/;
    return ipRegex.test(input) || cidrRegex.test(input);
  };

  // 开始扫描
  const handleStartScan = async () => {
    if (!ipInput.trim()) {
      messageApi.error('请输入IP地址或IP段');
      setInputShake(true);
      return;
    }
    if (!isValidIpOrCidr(ipInput.trim())) {
      messageApi.error('请输入合法的IP地址或IP网段，如 192.168.1.1 或 192.168.1.1/24');
      setInputShake(true);
      return;
    }
    setScanning(true);
    setTableData([]);
    setProjectId(null);
    setPageNum(1);
    try {
      // 启动扫描
      const res = await projectApi.startScan(ipInput.trim());
      if (res.code !== 0 || !res.data?.ID) {
        console.log("res:", res);
        messageApi.error(res.message || '启动扫描失败');
        setScanning(false);
        return;
      }
      const pid = res.data.ID;
      setProjectId(pid);
      messageApi.success('扫描已启动，正在查询进度...');
      refreshSiderMenu && refreshSiderMenu();
      // 轮询查询状态
      pollProjectStatus(pid);
    } catch (err: any) {
      messageApi.error(err?.response?.data?.message || err?.message || '启动扫描失败');
      setScanning(false);
    }
  };

  // 轮询查询项目状态
  const pollProjectStatus = async (pid: number, retry = 0) => {
    if (retry > 600) { // 最多轮询60次（约3分钟）
      messageApi.error('扫描超时');
      setScanning(false);
      return;
    }
    fetchScanResults(pid, pageNum);
    try {
      const res = await projectApi.getProject(pid);
      if (res.code !== 0 || !res.data) {
        messageApi.error(res.message || '查询扫描状态失败');
        setScanning(false);
        return;
      }
      console.log("res.data:", res.data);
      if (res.data.Status === 1) {
        // 扫描完成，查结果
        fetchScanResults(pid, pageNum);
        setScanning(false);
        messageApi.success('扫描完成');
        refreshSiderMenu && refreshSiderMenu();
      } else {
        // 继续轮询
        setTimeout(() => pollProjectStatus(pid, retry + 1), 3000);
      }
    } catch (err: any) {
      messageApi.error(err?.response?.data?.message || err?.message || '查询扫描状态失败');
      setScanning(false);
    }
  };

  // 查询扫描结果
  const fetchScanResults = async (pid: number, page: number = pageNum) => {
    try {
      const res = await scanResultApi.getScanResultsByProject(pid, { page, page_size: PAGE_SIZE });
      setTableData(res.data?.Data || []);
      setTotal(res.data?.TotalCount || 0);
    } catch (err: any) {
      messageApi.error(err?.response?.data?.message || err?.message || '获取扫描结果失败');
    }
  };
  const handleTableChange = (pagination: any) => {
    setPageNum(pagination.current);
    if (projectId !== null) {
      fetchScanResults(projectId, pagination.current);
    }
  };
  return (
    <div>
      {/* 操作区 */}
      <Card style={{ marginBottom: 16 }}>
        <Space.Compact style={{ width: '100%' }}>
          <Input
            placeholder="请输入IP地址(例如: 192.168.1.1)或IP段(例如: 192.168.1.1/24)"
            value={ipInput}
            onChange={(e) => setIpInput(e.target.value)}
            disabled={scanning}
            onPressEnter={handleStartScan}
            style={{ flex: 1 }}
            className={inputShake ? 'ip-input-shake' : ''}
            onAnimationEnd={() => setInputShake(false)}
          />
          <Button
            type="primary"
            icon={<PlayCircleOutlined />}
            onClick={handleStartScan}
            disabled={scanning}
            loading={scanning}
          >
            {scanning ? '扫描中' : '开始扫描'}
          </Button>
        </Space.Compact>
      </Card>

      {/* 扫描结果区 */}
      <Card>
        <Table
          columns={columns}
          dataSource={tableData}
          rowKey="ID"
          pagination={{ current: pageNum, pageSize: PAGE_SIZE, total: total, showSizeChanger: false }}
          onChange={handleTableChange}
        />
      </Card>
    </div>
  );
};

(ScanTool as any).title = '扫描工具';
export default ScanTool; 